<?php
/**
 * User administration interface, based on ModelAdmin
 * @package site
 */
class UserAdmin extends ModelAdmin {

    private static $url_segment = 'user';
    private static $menu_title = 'User';
    private static $menu_icon = 'general/images/user-icon.png';
	public $showImportForm = false;

    private static $managed_models = array(
    	'Member',
    	'Group'
    );
	
	public function init() {
		$extensions = Member::get_extensions('Member');
		foreach($extensions as $extension){
			if($extension == 'CustomMember' || $extension == 'Admin') continue;
			Member::remove_extension($extension);
		}
		
		parent::init();
	}
	
	public function getEditForm($id = null, $fields = null) {
        $list = $this->getList();
        $exportButton = new GridFieldExportButton('buttons-after-left');
        $exportButton->setExportColumns($this->getExportFields());
        
		if($this->modelClass == 'Member'){
			$listField = GridField::create(
	            $this->sanitiseClassName($this->modelClass),
	            false,
	            $list,
	            $fieldConfig = GridFieldConfig_RecordEditor::create($this->stat('page_length'))
					->removeComponentsByType('GridFieldDetailForm')
	                ->removeComponentsByType('GridFieldFilterHeader')
	                ->addComponents(new AdminGridFieldDetailForm(), new MemberGridFieldStatusAction(), new GridFieldButtonRow('after'), new GridFieldPrintButton('buttons-after-left'), $exportButton)
	        );
		
		}
		else if($this->modelClass == 'Group'){
			$listField = AdminGroupGridField::create(
	            $this->sanitiseClassName($this->modelClass),
	            false,
	            $list,
	            $fieldConfig = GridFieldConfig_RecordEditor::create($this->stat('page_length'))
					->removeComponentsByType('GridFieldDetailForm')
					->removeComponentsByType('GridFieldDeleteAction')
	                ->removeComponentsByType('GridFieldFilterHeader')
	                ->addComponents(new AdminGroupGridFieldDetailForm(), new AdminGroupGridFieldDeleteAction(), new GridFieldButtonRow('after'), new GridFieldPrintButton('buttons-after-left'), $exportButton)
	        );
		
		}
		else{
	        $listField = GridField::create(
	            $this->sanitiseClassName($this->modelClass),
	            false,
	            $list,
	            $fieldConfig = GridFieldConfig_RecordEditor::create($this->stat('page_length'))
	                ->removeComponentsByType('GridFieldFilterHeader')
	                ->addComponents(new GridFieldButtonRow('after'), new GridFieldPrintButton('buttons-after-left'), $exportButton)
	        );
		}
        
		// Validation
        if(singleton($this->modelClass)->hasMethod('getCMSValidator')) {
            $detailValidator = singleton($this->modelClass)->getCMSValidator();
			if($this->modelClass == 'Member'){
				$listField->getConfig()->getComponentByType('AdminGridFieldDetailForm')->setValidator($detailValidator);
			}
			else if($this->modelClass == 'Group'){
				$listField->getConfig()->getComponentByType('AdminGroupGridFieldDetailForm')->setValidator($detailValidator);
			}
			else{
            	$listField->getConfig()->getComponentByType('GridFieldDetailForm')->setValidator($detailValidator);
			}
        }
		
		$note = new LiteralField('MembersCautionText',
			sprintf('<p class="caution-remove"><strong>%s</strong></p>',
				_t(
					'UserAdmin.MemberListCaution', 
					'Caution: Removing users from this list will remove them from all groups and the'
						. ' database'
				)
			)
		);

        $form = CMSForm::create( 
            $this,
            'EditForm',
            new FieldList($listField, $note),
            new FieldList()
        )->setHTMLID('Form_EditForm');
		$form->setResponseNegotiator($this->getResponseNegotiator());
        $form->addExtraClass('cms-edit-form cms-panel-padded center');
        $form->setTemplate($this->getTemplatesWithSuffix('_EditForm'));
        $editFormAction = Controller::join_links($this->Link($this->sanitiseClassName($this->modelClass)), 'EditForm');
        $form->setFormAction($editFormAction);
        $form->setAttribute('data-pjax-fragment', 'CurrentForm');

        $this->extend('updateEditForm', $form);
        
        return $form;
    }

	public function getList() {
		$context = $this->getSearchContext();
		$params = $this->request->requestVar('q');
		$list = $context->getResults($params);
		
		if($this->modelClass == 'Member'){
			$list = $list->filter('IsAdmin', 1)->exclude(Config::inst()->get('Member', 'unique_identifier_field'), Security::default_admin_username());
		}
		else if($this->modelClass == 'Group'){
			$exclude = (array)Member::currentUser()->Groups()->map('ID', 'Code')->toArray();
			$exclude[] = 'administrators';
			$list = $list->filter('IsAdminGroup', 1)->exclude('Code', $exclude);
		}

		$this->extend('updateList', $list);

		return $list;
	}

	public function getManagedModels() {
		$models = $this->stat('managed_models');
		if(is_string($models)) {
			$models = array($models);
		}
		if(!count($models)) {
			user_error(
				'ModelAdmin::getManagedModels(): 
				You need to specify at least one DataObject subclass in public static $managed_models.
				Make sure that this property is defined, and that its visibility is set to "public"', 
				E_USER_ERROR
			);
		}

		// Normalize models to have their model class in array key
		foreach($models as $k => $v) {
			if(is_numeric($k)) {
				if($v == 'Group'){
					if(!Permission::check('EDIT_GROUPS') && Member::currentUserID()){
						unset($models[$k]);
						continue;
					}
				}
				else{
					if(!singleton($v)->canView() && Member::currentUserID()){
						unset($models[$k]);
						continue;
					}
				}
				$models[$v] = array('title' => singleton($v)->i18n_singular_name());
				unset($models[$k]);
			}
			else{
				if($k == 'Group'){
					if(!Permission::check('EDIT_GROUPS') && Member::currentUserID()){
						unset($models[$k]);
						continue;
					}
				}
				else{
					if(!singleton($k)->canView() && Member::currentUserID()){
						unset($models[$k]);
						continue;
					}
				}
			}
		}
		
		return $models;
	}
}
?>